<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2023/6/1
 * Time: 16:07
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);


namespace App\Common\Business;

use App\Common\Lib\Log\Log;
use App\Exception\FooException;
use App\Model\Cart;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class CartBusiness extends BusBase
{
    protected $obj_model;
    /**
     * @var AuthManager
     */
    #[Inject]
    protected AuthManager $auth;

    public function __construct()
    {
        $this->obj_model = new Cart();
    }

    public function getCartGoodsId(array $sku_id = [], int $user_id = 0): array
    {
        try {
            $result = $this->obj_model
                ->whereIn('sku_id', $sku_id)
                ->where('user_id', $user_id)
                ->with(['goods', 'goodsSku'])
                ->get()
                ->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        return $result;
    }

    /**
     * @param int $goods_id
     * @param int $user_id
     * @return array
     */
    public function getUserCartGoodsId(int $goods_id = 0, int $user_id = 0): array
    {
        try {
            $result = $this->obj_model->where('goods_id', $goods_id)
                ->where('user_id', $user_id)
                ->first();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        if (!$result) {
            return [];
        } else {
            return $result->toArray();
        }
    }

    /**
     * 设置数量
     * @param int $sku_id
     * @param string $type
     * @param array $data
     * @return bool
     */
    public function setUserCartByInfo(int $sku_id = 0, string $type = 'inc', array $data = []): bool
    {
        if ($sku_id == 0) {
            throw new FooException("操作失败");
        }
        $user_id = $this->auth->guard('jwt')->id();
        try {
            $result = $this->obj_model
                ->where('sku_id', $sku_id)
                ->where('user_id', $user_id)
                ->first();
            if (!$result && $type == 'inc') {
                $res = $this->obj_model->insert([
                    'sku_id' => $sku_id,
                    'user_id' => $user_id,
                    'quantity' => 1,
                    'goods_id' => $data['goods_id'],
                    'specs_value' => $data['specs_value'],
                    'create_time' => time(),
                    'update_time' => time()
                ]);
            } else if ($type == 'inc') {
                $res = $result->increment('quantity');
            } else {
                if ($result['quantity'] == 1) {
                    $res = $result->forceDelete();
                } else {
                    $res = $result->decrement('quantity');
                }
            }
        } catch (\Exception $e) {
            Log::get('cart-setUserCart', 'error')->error($e->getMessage());
            throw new FooException("查询失败");
        }
        if (!$res) {
            throw new FooException("操作失败");
        }
        return true;
    }

    /**
     * @param int $id
     * @param int $number
     * @return true
     */
    public function changeCart(int $id = 0, int $number = 0)
    {
        try {
            $this->obj_model->where('id', $id)->update(['quantity' => $number, 'update_time' => time()]);
        } catch (\Exception $e) {
            throw new FooException("操作失败");
        }
        return true;
    }

    public function clearCart()
    {
        $user_id = $this->auth->id();
        try {
            $result = $this->obj_model->where('user_id', $user_id)->forceDelete();
        } catch (\Exception $e) {
            throw new FooException("操作失败");
        }
        if (!$result) {
            throw new FooException("操作失败");
        }
        return true;
    }

    /**
     * 删除
     * @param int $id
     * @return true
     */
    public function delCartInfo(int $id = 0)
    {
        $user_id = $this->auth->id();
        try {
            $this->obj_model
                ->where('id', $id)
                ->where('user_id', $user_id)
                ->forceDelete();
        } catch (\Exception $e) {
            throw new FooException("删除失败");
        }
        return true;
    }

    /**
     * 获取购物车列表
     * @return array
     */
    public function getUserCartList()
    {
        $user_id = $this->auth->id();
        try {
            $lists = $this->obj_model
                ->join('goods_sku', 'cart.sku_id', '=', 'goods_sku.id')
                ->join('goods', 'goods_sku.goods_id', '=', 'goods.id')
                ->where('cart.user_id', $user_id)
                ->get(['goods_sku.image', 'cart.sku_id', 'cart.id', 'cart.quantity as number', 'goods_sku.stock', 'goods_sku.price', 'cart.specs_value', 'goods.title'])
                ->toArray();
        } catch (\Exception $e) {
            throw new FooException("查询失败");
        }
        return $lists;
    }
}